import fs from 'fs';
import configTool from '../../com/configTool';
import path from 'path';

enum RouteType {
    client = 'client',
    manage = 'manage'
}


function logHandler(routeType: RouteType) {
    return async (ctx: any, next: Function) => {
        await configTool.init();

        const logObj = {
            ip: ctx.request.ip,
            method: ctx.request.method,
            start: new Date().toLocaleString(),
            passSecond: 0,
            url: decodeURI(ctx.request.url)
        };
        await next();

        if (logObj.url.includes('/Resources/') || logObj.url.includes('/favicon.ico')) {
            return;
        }

        logObj.passSecond = (new Date().getTime() - new Date(logObj.start).getTime()) / 1000;


        if (routeType === RouteType.client) {
            fs.appendFileSync(path.join(configTool.appBasePath, '/temp/logs/clientServer/WebLog.json'), JSON.stringify(logObj) + ',\n');
        } else {
            fs.appendFileSync(path.join(configTool.appBasePath, '/temp/logs/manageServerPort/WebLog.json'), JSON.stringify(logObj) + ',\n');
        }
    };
}


export default logHandler;
